<template>
  <div class="see-container">
    <h1>SEE 连接</h1>
    <div class="connection-status">
      状态: {{ connectionStatus }}
    </div>
    <div class="input-area">
      <input v-model="userInput" @keyup.enter="sendMessage" placeholder="输入消息..." />
      <button @click="sendMessage">发送</button>
    </div>
    <div class="output-area">
      <div v-if="messages.length === 0" class="no-messages">暂无消息</div>
      <div v-else class="message-list">
        <div v-for="(message, index) in messages" :key="index" class="message">
          <div class="message-type">{{ message.type }}</div>
          <div class="message-content">{{ message.content }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SeeView',
  data() {
    return {
      connectionStatus: '未连接',
      userInput: '',
      messages: [],
      streamingMessage: '',
      eventSource: null
    }
  },
  mounted() {
    this.connectSSE()
  },
  beforeUnmount() {
    if (this.eventSource) {
      this.eventSource.close()
    }
  },
  methods: {
    connectSSE() {
      // 关闭之前的连接（如果存在）
      if (this.eventSource) {
        this.eventSource.close()
      }
      
      // 创建新的SSE连接
      this.eventSource = new EventSource('http://localhost:8000/sse')
      
      this.connectionStatus = '正在连接'
      console.log('正在连接SSE...')
      
      // 监听连接打开事件
      this.eventSource.onopen = () => {
        console.log('SSE连接已打开')
        this.connectionStatus = '已连接'
        this.messages.push({
          type: '系统',
          content: '连接已建立'
        })
      }
      
      // 监听消息事件
      this.eventSource.onmessage = (event) => {
        console.log('收到SSE消息:', event.data)
        
        // 处理消息
        if (event.data === '[END]') {
          // 流式消息结束
          this.messages.push({
            type: '接收',
            content: this.streamingMessage
          })
          this.streamingMessage = ''
        } else if (event.data === 'ping') {
          // 心跳消息，忽略
          console.log('收到心跳消息')
        } else if (event.data === '连接已建立') {
          // 连接确认消息，已在onopen中处理
          console.log('收到连接确认消息')
        } else {
          // 流式消息内容
          this.streamingMessage += event.data
          
          // 更新或添加流式消息
          const lastMessage = this.messages[this.messages.length - 1]
          if (this.messages.length > 0 && lastMessage.type === '流式') {
            lastMessage.content = this.streamingMessage
          } else {
            this.messages.push({
              type: '流式',
              content: this.streamingMessage
            })
          }
        }
      }
      
      // 监听错误事件
      this.eventSource.onerror = (error) => {
        console.error('SSE连接错误:', error)
        this.connectionStatus = '错误'
        this.messages.push({
          type: '错误',
          content: '连接发生错误'
        })
        
        // 尝试重新连接
        setTimeout(() => {
          console.log('尝试重新连接SSE...')
          this.connectSSE()
        }, 3000)
      }
    },
    
    sendMessage() {
      if (!this.userInput.trim()) {
        return
      }
      
      console.log('发送消息:', this.userInput)
      
      // 通过HTTP POST发送消息
      fetch('http://localhost:8000/send', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ message: this.userInput })
      })
      .then(response => {
        if (!response.ok) {
          throw new Error('发送消息失败')
        }
        return response.json()
      })
      .then(data => {
        console.log('发送消息成功:', data)
        this.messages.push({
          type: '发送',
          content: this.userInput
        })
        this.userInput = ''
      })
      .catch(error => {
        console.error('发送消息错误:', error)
        this.messages.push({
          type: '错误',
          content: `发送消息失败: ${error.message}`
        })
      })
    }
  }
}
</script>

<style scoped>
.see-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.connection-status {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.input-area {
  display: flex;
  margin-bottom: 20px;
}

.input-area input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
}

.input-area button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.output-area {
  border: 1px solid #ddd;
  border-radius: 4px;
  height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.no-messages {
  color: #999;
  text-align: center;
  margin-top: 180px;
}

.message {
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.message-type {
  font-weight: bold;
  margin-bottom: 5px;
}

.message-content {
  white-space: pre-wrap;
  word-break: break-word;
}
</style>